<template>
  <div class="search">
    <form action="/">
      <van-search
      background= "#3296fa"
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isShowRes = false"
      />
    </form>
    <search-result v-if="isShowRes" :searchText="value"></search-result>
    <search-history @clear="history = []" :history="history" @onSearch="onSearch" v-else-if="!value"></search-history>
    <search-suggestion @onSearch="onSearch" :searchText="value" v-else></search-suggestion>
  </div>
</template>

<script>
// import { Toast } from 'vant'
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResult from './components/SearchResult.vue'
import { setStorage, getStorage } from '@/utils/storage.js'
export default {
  components: { SearchHistory, SearchSuggestion, SearchResult },
  name: 'search',
  data () {
    return {
      value: '',
      isShowRes: false,
      history: getStorage('TT-HISTORY') || [] // 储存搜索历史
    }
  },

  created () {

  },

  watch: {
    history: {
      deep: true,
      handler (Val) {
        setStorage('TT-HISTORY', Val)
      }
    }
  },

  methods: {
    onSearch (Val) {
      this.value = Val
      this.isShowRes = true
      this.history.unshift(Val)
      this.history = [...new Set(this.history)]
    }
  }
}
</script>

<style scoped lang='less'>
.search {
  .van-search__action{
    color: #fff;
  }
}
</style>
